//
//  WNRateVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/8/28.
//

import UIKit

class WNRateVC: WNBaseVC {
    
    lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.textColor = .init(named: "black_333333")
        label.font = .wn_font(name: .bold, size: 18)
        label.text = "Rate this book"
        return label
    }()
    
    lazy var starView: RateStarView = {
        let view = RateStarView()
        return view
    }()
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setBackgroundImage(UIImage(named: "rate_close"), for: .normal)
        btn.rx.tap.bind { [weak self] in
            self?.finshClosure?("Cancel")
        }.disposed(by: rx.disposeBag)
        return btn
    }()
    
    lazy var submitBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "rank_send_white"), for: .normal)
        btn.setTitle("Post", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 16)
        btn.rx.tap.bind { [weak self] in
            self?.rateRequest()
        }.disposed(by: rx.disposeBag)
        btn.backgroundColor = WNColor.Fade().left2right(.init(width: scaleWidth(240), height: 44))
        btn.wn_cornerWithBorder(20)
        btn.alpha = 0.6
        btn.isEnabled = false
        return btn
    }()
    
    lazy var textView: IQTextView = {
        let view = IQTextView()
        view.textContainerInset = .init(top: 10, left: 10, bottom: 10, right: 10)
        view.placeholder = "Review should be 10-300 characters."
        view.font = .wn_font(name: .regular, size: 14)
        view.tintColor = .init(named: "red_FE95B4")
        view.textColor = .init(named: "black_333333")
        view.returnKeyType = .done
        view.keyboardDismissMode = .none
        view.textContainer.lineFragmentPadding = 10
        view.delegate = self
        return view
    }()
    
    lazy var toplineView: UIView = {
        let view = UIView()
        view.backgroundColor = .init(named: "gray_E0E8EE")
        return view
    }()
    
    lazy var bomlineView: UIView = {
        let view = UIView()
        view.backgroundColor = .init(named: "gray_E0E8EE")
        return view
    }()
    
    lazy var countLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 12)
        label.textColor = .init(named: "gray_666666")
        label.text = "0/300"
        return label
    }()
    
    var finshClosure: StringClosure?
    
    var currentText: String = "" {
        didSet {
            let str = currentText.trimmingCharacters(in: .whitespacesAndNewlines)
            countLabel.text = "\(currentText.count)/300"
            submitBtn.isEnabled = str.count > 10
            submitBtn.alpha = str.count > 10 ? 1 : 0.6
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        wn_hidNavView()
        view.addSubview(nameLabel)
        view.addSubview(closeBtn)
        view.addSubview(starView)
        view.addSubview(toplineView)
        view.addSubview(submitBtn)
        view.addSubview(countLabel)
        view.addSubview(bomlineView)
        view.addSubview(textView)
        nameLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(20)
            make.height.equalTo(25)
        }
        closeBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(nameLabel.snp.centerY)
            make.right.equalTo(-16)
            make.width.height.equalTo(32)
        }
        starView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(nameLabel.snp.bottom).offset(32)
            make.width.equalTo(264)
            make.height.equalTo(36)
        }
        toplineView.snp.makeConstraints { (make) in
            make.top.equalTo(starView.snp.bottom).offset(20)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(1)
        }
        submitBtn.snp.makeConstraints { (make) in
            make.bottom.equalTo(-8-TabBarMargin)
            make.right.equalTo(-20)
            make.width.equalTo(scaleWidth(240))
            make.height.equalTo(44)
        }
        countLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(submitBtn.snp.centerY)
            make.left.equalTo(20)
        }
        bomlineView.snp.makeConstraints { (make) in
            make.bottom.equalTo(submitBtn.snp.top).offset(-8)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(1)
        }
        textView.snp.makeConstraints { (make) in
            make.top.equalTo(toplineView.snp.bottom).offset(20)
            make.bottom.equalTo(bomlineView.snp.top).offset(-20)
            make.left.equalTo(20)
            make.right.equalTo(-20)
        }
        submitBtn.layoutButton(style: .left, imageTitleSpace: 10)
        view.wn_cornerCustom([.topLeft, .topRight], 20)
    }
    
    override func dataConfig() {
        
    }
}

extension WNRateVC: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        if textView.text.count > WNRegex.RateMaxLen {
            let selectRange = textView.markedTextRange
            if let selectRange = selectRange {
                let position = textView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }
            let textContent = textView.text
            let textNum = textContent?.count
            if textNum! > WNRegex.RateMaxLen {
                let index = textContent?.index((textContent?.startIndex)!, offsetBy: WNRegex.RateMaxLen)
                let str = String(textContent![..<index!])
                textView.text = str
            }
            WNHUD.wn_show("Max of comments in \(WNRegex.RateMaxLen) words")
            WNThread.wn_runInMainThread {
                self.textView.selectedTextRange = self.textView.textRange(from: self.textView.endOfDocument, to: self.textView.endOfDocument)
            }
        }
        currentText = textView.text
    }
    
    func heightForTextView(textView: UITextView, fixedWidth: CGFloat) -> CGFloat {
        let size = CGSize(width: fixedWidth, height: 16)
        let constraint = textView.sizeThatFits(size)
        return constraint.height
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            rateRequest()
            return false
        }
        return true
    }
        
    func rateRequest() {
        let text = currentText.trimmingCharacters(in: .whitespacesAndNewlines)
        guard text.count > 9 else {
            wn_toast("Review more than 10 characters")
            return
        }
        textView.resignFirstResponder()
    }
}

class RateStarView: UIView {
    
    var btnArr = [UIButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        for i in 0..<5 {
            let btn = UIButton(type: .custom)
            btn.tag = i
            btn.frame = CGRect(x: i*(36+21), y: 0, width: 36, height: 36)
            btn.setImage(UIImage(named: "rank_star"), for: .normal)
            btn.setImage(UIImage(named: "rank_stared"), for: .selected)
            btn.setImage(UIImage(named: "rank_stared"), for: .highlighted)
            btn.rx.tap.bind { [weak self] in
                self?.handeBtn(btn.tag)
            }.disposed(by: rx.disposeBag)
            btnArr.append(btn)
            addSubview(btn)
        }
    }
    
    func handeBtn(_ tag: Int) {
        for i in btnArr {
            i.isSelected = (i.tag <= tag)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
